package com.xinlong.shop.core.promotion.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinlong.shop.core.member.BalanceTypeEnum;
import com.xinlong.shop.core.member.entity.MemberBalanceDetail;
import com.xinlong.shop.core.member.service.IMemberBalanceDetailService;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.core.promotion.entity.PutSaleOrder;
import com.xinlong.shop.core.promotion.mapper.PutSaleOrderMapper;
import com.xinlong.shop.core.promotion.service.IPutSaleOrderService;
import com.xinlong.shop.core.promotion.service.IRushPurchaseDetailService;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.exception.ServiceException;
import com.xinlong.shop.framework.service.ISysSettingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 上架订单列表 服务实现类
 * </p>
 *
 * @author Sylow
 * @since 2023-03-29
 */
@Service
public class PutSaleOrderServiceImpl extends ServiceImpl<PutSaleOrderMapper, PutSaleOrder> implements IPutSaleOrderService {

    private final IRushPurchaseDetailService rushPurchaseDetailService;
    private final IMemberService memberService;
    private final ISysSettingService sysSettingService;
    private final IMemberBalanceDetailService memberBalanceDetailService;

    public PutSaleOrderServiceImpl(IRushPurchaseDetailService rushPurchaseDetailService, IMemberService memberService, ISysSettingService sysSettingService, IMemberBalanceDetailService memberBalanceDetailService) {
        this.rushPurchaseDetailService = rushPurchaseDetailService;
        this.memberService = memberService;
        this.sysSettingService = sysSettingService;
        this.memberBalanceDetailService = memberBalanceDetailService;
    }

    @Override
    public boolean update(PutSaleOrder putSaleOrder, Integer id) {
        UpdateWrapper<PutSaleOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        return this.update(putSaleOrder, updateWrapper);
    }
    @Override
    public void delete(Integer id) {
        UpdateWrapper<PutSaleOrder> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("id", id);
        this.remove(deleteWrapper);
    }

    @Override
    public PutSaleOrder findByDetailId(Integer detailId) {
        QueryWrapper<PutSaleOrder> query = new QueryWrapper<>();
        query.eq("rush_purchase_detail_id", detailId);
        return this.getOne(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void putSaleOrder(String orderSn, String payOrderSn) {

        // 先拿到此次订单信息
        QueryWrapper<PutSaleOrder> query = new QueryWrapper<>();
        query.eq("order_sn", orderSn);
        PutSaleOrder putSaleOrder = this.getOne(query);
        if (putSaleOrder == null) {
            throw new ServiceException("找不到此订单");
        }

        if (putSaleOrder.getStatus() == 1) {
            throw new ServiceException("此订单已经支付");
        }

        // 进行上架操作 并且获得上架后的活动详情id
        Integer nextPurchaseDetailId = rushPurchaseDetailService.putSale(putSaleOrder.getRushPurchaseDetailId(), putSaleOrder);

        // 先保存此次的支付单号
        UpdateWrapper<PutSaleOrder> update = new UpdateWrapper<>();
        update.set("next_rush_purchase_detail_id", nextPurchaseDetailId);
        update.set("status", 1);
        update.set("payment_order_no", payOrderSn);
        update.eq("order_sn", orderSn);
        this.update(update);

        // 向邀请人返利
        MemberBalanceDetail memberBalanceDetail = memberBalanceDetailService.findBySource(putSaleOrder.getOrderSn());
        // 如果该订单没有返利过（防止重复）
        if (memberBalanceDetail == null) {
            // 得到邀请人
            Member inviter = memberService.getInviteeMemberByMemberId(putSaleOrder.getMemberId());
            if (inviter != null) {
                // 得到本人
                Member member = memberService.getById(putSaleOrder.getMemberId());
                Map<String, Object> setting = sysSettingService.getSetting();
                Double putSalePriceCommission = (Double)setting.get("putSalePriceCommission");

                BigDecimal commissionPrice = NumberUtil.mul(putSaleOrder.getOriginalPrice(), putSalePriceCommission);
                commissionPrice= NumberUtil.div(commissionPrice, 100, 2);
                memberBalanceDetailService.add(inviter.getId(), putSaleOrder.getOrderSn(), BalanceTypeEnum.SERVICE_CHARGE.getCode(),
                        commissionPrice, "被推广人：" + member.getNickname());

            }
        }

    }

    public static void main(String[] args) {
        System.out.println(NumberUtil.mul(10400, 0.5));
    }

    @Override
    public boolean savePutSaleOrder(PutSaleOrder putSaleOrder) {
        String orderSn = putSaleOrder.getOrderSn();
        QueryWrapper<PutSaleOrder> query = new QueryWrapper<>();
        query.eq("order_sn", orderSn);
        PutSaleOrder tempOrder = this.getOne(query);
        // 防止重复保存
        if (tempOrder == null) {
            return this.save(putSaleOrder);
        } else {
            return true;
        }
    }

    @Override
    public List<PutSaleOrder> findByMemberId(Integer memberId) {
        QueryWrapper<PutSaleOrder> query = new QueryWrapper<>();
        query.eq("member_id", memberId);
        query.eq("status", 0);
        return this.list(query);
    }

}
